/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.listener;

import com.bifrost.entity.CouponDetail;
import com.bifrost.entity.Customer;
import com.bifrost.entity.MerchantStore;
import com.bifrost.event.CouponUpdatedEvent;
import com.bifrost.wechat.entity.WechatAccount;
import com.bifrost.wechat.service.WechatAccountService;
import com.bifrost.wechat.service.WxServiceContext;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 *@author joewee
 *@version 1.0.0
 *@Date 2018/5/14 19:37
 */
@Component
@Async
public class CouponUpdatedListener implements ApplicationListener<CouponUpdatedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(CouponUpdatedListener.class);
    @Value("${template.coupon.message:#{null}}")
    String templateId;
    @Autowired
    private WxServiceContext wxServiceContext;
    @Autowired
    WechatAccountService wechatAccountService;
    @Override
    public void onApplicationEvent(CouponUpdatedEvent couponUpdatedEvent) {
       CouponDetail couponDetail =(CouponDetail) couponUpdatedEvent.getSource();
        if (couponDetail !=null) {
            if (StringUtils.isNotBlank(templateId))
            {
               Customer customer = couponDetail.getCustomer();
                WxMpTemplateData subTitle = new WxMpTemplateData("first", String.format("尊敬的郁美荟会员：大坪商都感谢您对我商都的持续关注与支持，现送您%s，以表谢意",couponDetail.getCouponName()), "#173177");
                WxMpTemplateData orderNumber = new WxMpTemplateData("keyword1", couponDetail.getCouponName(), "#173177");
                WxMpTemplateData total = new WxMpTemplateData("keyword2", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(couponDetail.getAddTime()), "#173177");
                WxMpTemplateData remark = new WxMpTemplateData("remark", "进入会员中心“我的优惠券”中查看，祝您用券愉快。", "#173177");
                List<WxMpTemplateData> dataList = new ArrayList<>();
                dataList.add(subTitle);
                dataList.add(orderNumber);
                dataList.add(total);
                dataList.add(remark);
                WxMpTemplateMessage message = WxMpTemplateMessage.builder()
                        .templateId(templateId).toUser(customer.getOpenId()).url("")
                        .data(dataList).build();
                try {
                    MerchantStore releaseBy = couponDetail.getReleaseBy();
                    if(releaseBy==null){
                        releaseBy = customer.getMerchantStore();
                    }
                    if (releaseBy!= null){
                        Long storeId = releaseBy.getMerchantId();
                        WechatAccount account = wechatAccountService.getAccount(storeId);
                        if (account != null) {
                            WxMpService service = wxServiceContext.getWxServiceByAppId(account.getAppId());
                            service.getTemplateMsgService().sendTemplateMsg(message);
                        }
                    }else {
                        LOGGER.warn("发送消息模板失败..门店：%s 获取不到");
                    }
                } catch (WxErrorException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }


        }
    }
}
